package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;

import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 文章发布功能
     * @param newsId 文章id
     */
    @GlobalTransactional
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 查询并检查自媒体文章  wmNews
        WmNews wmNews = checkAndGetWmNews(newsId);
        // 2. 封装 ApArticle
        ApArticle apArticle = setApArticle(wmNews);
        // 3. 保存或修改 article信息
        saveOrUpdateArticle(apArticle);
        // 4. 保存关联配置和内容信息
        saveConfigAndConent(wmNews, apArticle);
        // 5. TODO 文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        // 6. 更新 wmNews状态  改为9  并设置articleId set只能设置定义的枚举类，用常量类的9不行
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.checkCode()){
            log.error("文章发布失败 远程调用修改文章接口失败， 不予发布 , 文章id : {} ",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用修改文章接口失败");
        }
        // 7. TODO 通知es索引库添加文章索引

    }


    /**
     * 根据参数加载文章列表
     * @param loadtype  0为加载更多  1为加载最新
     * @param dto
     * @param firstPage 是否为首页 true 首页
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtype, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage) {
            // redis
            String articleListJson = (String) redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListJson)) {
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
                }
                ResponseResult result = ResponseResult.okResult(apArticles);
                result.setHost(webSite);

                return result;
            }
        }

        return load(loadtype, dto);
    }

    /**
     * 根据参数加载文章列表
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //查询
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        //前端以http为条件判断是否显示图片，需要加前缀websit
        for (ApArticle apArticle : apArticles) {
            // 获取文章封面图片，取出每一个图片以，分割然后加前缀
            String images = apArticle.getImages();
            images = Arrays.stream(images.split(",")).map(url ->
                webSite + url
            ).collect(Collectors.joining(","));
            apArticle.setImages(images);
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }

        return ResponseResult.okResult(apArticles);
    }

    private void saveConfigAndConent(WmNews wmNews, ApArticle apArticle) {
        // 添加配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        // 添加文章详情
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    /**
     * 保存或修改文章信息
     * @param apArticle
     */
    private void saveOrUpdateArticle(ApArticle apArticle) {
        //如果查询到文章信息为空，为其保存信息
        if (apArticle.getId() == null) {
            // 保存文章
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            save(apArticle);
        } else {
            //不为null代表有关联的信息,需要删除
            ApArticle article = getById(apArticle.getId());
            if(article == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的文章不存在");
            }
            updateById(apArticle);
            //删除配置表，内容表的信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
        }
    }

    /**
     * 封装ApArticle
     * @param wmNews
     * @return
     */
    private ApArticle setApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        //封装属性
        BeanUtils.copyProperties(wmNews,apArticle);
        //设置关联和独立属性
        apArticle.setId(wmNews.getArticleId());
        //文章类型 0 普通文章   1 热点文章   2 置顶文章   3 精品文章   4 大V 文章
        apArticle.setFlag((byte) 0);
        //文章布局  0 无图文章   1 单图文章    2 多图文章 与文章表type关联
        apArticle.setLayout(wmNews.getType());
        // 远程查询频道信息
        ResponseResult<AdChannel> adminFeignOne = adminFeign.findOne(wmNews.getChannelId());
        if (!adminFeignOne.checkCode()) {
            log.error("文章发布失败 远程调用查询频道出现异常， 不予发布 , 文章id : {}  频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用查询频道出现异常");
        }
        AdChannel adChannel = adminFeignOne.getData();
        if (adChannel == null) {
            log.error("未查询到相关频道信息");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apArticle.setChannelName(adChannel.getName());
        apArticle.setChannelId(adChannel.getId());
        // 设置作者信息
        //selectById只能根据主键查询，不是主键查询为null
        //ApAuthor apAuthor = authorMapper.selectById(wmNews.getUserId());
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            log.error("未查询到作者信息");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apArticle.setAuthorName(apAuthor.getName());
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        return apArticle;
    }

    /**
     * 查询并检查自媒体文章
     * @param newsId
     * @return
     */
    private WmNews checkAndGetWmNews(Integer newsId) {
        ResponseResult<WmNews> wmNewsById = wemediaFeign.findWmNewsById(newsId);
        if (!wmNewsById.checkCode()) {
            log.error("文章发布失败 远程调用自媒体文章接口失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用自媒体文章接口失败");
        }
        WmNews wmNews = wmNewsById.getData();
        if (wmNews == null) {
            log.error("文章不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 判断状态是否为 4 或 8， 如果不是  不处理
        Short status = wmNews.getStatus().shortValue();
        if(status!=WmNews.Status.ADMIN_SUCCESS.getCode() && status!=WmNews.Status.SUCCESS.getCode()){
            log.error("文章发布失败 文章状态不为 4 或 8， 不予发布");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"自媒体文章状态错误");
        }
        return wmNews;
    }
}